import logging

import cherrypy

import turbogears
from turbogears import controllers, expose, validate, redirect
from turbogears import identity
from turbogears.database import session

from simpleblog import json, model

log = logging.getLogger("simpleblog.controllers")

class AdminController(controllers.Controller, identity.SecureResource):
    require = identity.not_anonymous()
    
    @expose(template="simpleblog.templates.admin.index")
    def index(self):
        drafts = model.Post.select_by(is_published = False)
        published = model.Post.select_by(is_published = True)
        return dict(drafts=drafts, published=published)
        
    @expose(template="simpleblog.templates.admin.write")
    def write(self):
        return dict()
        
    @expose(template="simpleblog.templates.admin.edit")
    def edit(self, id):
        p = model.Post.get(int(id))
        return dict(post=p)
        
    @expose()
    def save(self, id=None, *args, **kw):
        referer = cherrypy.request.headerMap.get('Referer', '/admin/')
        if id:
            p = model.Post.get(int(id))
        else:
            p = model.Post()
            
        p.title = kw['title']
        p.content = kw['content']
        if "publish" in kw.keys():
            p.is_published = True
        p.flush()
        turbogears.flash("Post %d saved." % p.id)
        raise redirect("/post?id=%d" % p.id)

class Root(controllers.RootController):
    
    admin = AdminController()
    
    @expose(template="simpleblog.templates.index")
    def index(self):
        posts = model.Post.select()
        return dict(posts=posts)
        
    @expose(template="simpleblog.templates.post")
    def post(self, id):
        p = model.Post.get(int(id))
        return dict(post=p)
        
    @expose()
    def comment(self, post_id, author_name, author_email,
                content, author_url=None, *args, **kw):
        referer = cherrypy.request.headerMap.get("Referer", "/")
        p = model.Post.get(int(post_id))
        c = model.Comment(post=p, author_name=author_name,
                            author_email=author_email,
                            content=content)
        if author_url:
            c.author_url = author_url
        c.flush()
        raise redirect(referer)

    @expose(template="simpleblog.templates.login")
    def login(self, forward_url=None, previous_url=None, *args, **kw):

        if not identity.current.anonymous \
            and identity.was_login_attempted() \
            and not identity.get_identity_errors():
            raise redirect(forward_url)

        forward_url=None
        previous_url= cherrypy.request.path

        if identity.was_login_attempted():
            msg=_("The credentials you supplied were not correct or "
                   "did not grant access to this resource.")
        elif identity.get_identity_errors():
            msg=_("You must provide your credentials before accessing "
                   "this resource.")
        else:
            msg=_("Please log in.")
            forward_url= cherrypy.request.headers.get("Referer", "/")
        cherrypy.response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                    original_parameters=cherrypy.request.params,
                    forward_url=forward_url)

    @expose()
    def logout(self):
        identity.current.logout()
        raise redirect("/")
